﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace AspDotNet.Framework.Mvc.FirstDemo.Controllers
{
    [RoutePrefix("Filter")]
    public class FilterController : BaseController
    {
        /***
         * 四种过滤器:权限过滤器-->动作过滤器-->结果过滤器-->异常过滤器
         * 过滤器的注册:
         */
        [HandleError]
        public ActionResult HandleError()
        {
            throw new NotImplementedException();
        }

        [Authorize]
        public ActionResult Authorize()
        {
            return View();
        }

        [FirstDemoAuthorize]
        public ActionResult FirstDemoAuthorize()
        {
            return View();
        }

        [Log]
        public ActionResult ActionFilter()
        {
            return View();
        }
    }

    public class LogAttribute : ActionFilterAttribute/* 动作过滤器,结果过滤器 */
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            Log("OnActionExecuted", filterContext.RouteData);
            base.OnActionExecuted(filterContext);
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Log("OnActionExecuting", filterContext.RouteData);
            base.OnActionExecuting(filterContext);
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            Log("OnResultExecuted", filterContext.RouteData);
            base.OnResultExecuted(filterContext);
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            Log("OnResultExecuting ", filterContext.RouteData);
            base.OnResultExecuting(filterContext);
        }
        private void Log(string methodName, RouteData routeData)
        {
            var controllerName = routeData.Values["controller"];
            var actionName = routeData.Values["action"];
            var message = String.Format("{0}- controller:{1} action:{2}", methodName,
                                                                        controllerName,
                                                                        actionName);
            Debug.WriteLine(message);
        }
    }

    public class FirstDemoAuthorizeAttribute : AuthorizeAttribute
    {

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            filterContext.HttpContext.Response.Write("授权过滤器 --在Action过滤器前执行<br/>");
            base.OnAuthorization(filterContext);
        }
    }

}